package cn.wolfcode.car.business.service.impl;


import cn.wolfcode.car.business.domain.BpmnInfo;
import cn.wolfcode.car.business.mapper.BpmnInfoMapper;
import cn.wolfcode.car.business.query.BpmnInfoQuery;
import cn.wolfcode.car.business.service.IBpmnInfoService;
import cn.wolfcode.car.common.base.page.TablePageInfo;
import cn.wolfcode.car.common.config.SystemConfig;
import cn.wolfcode.car.common.util.Convert;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import org.activiti.bpmn.model.BpmnModel;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.image.impl.DefaultProcessDiagramGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.*;
import java.util.Collections;
import java.util.Date;
import java.util.List;

@Service
@Transactional
public class BpmnInfoServiceImpl extends ServiceImpl<BpmnInfoMapper,BpmnInfo> implements IBpmnInfoService{

    @Autowired
    private BpmnInfoMapper bpmnInfoMapper;
    @Autowired
    private RepositoryService repositoryService;

    @Override
    public TablePageInfo<BpmnInfo> query(BpmnInfoQuery qo) {
        PageHelper.startPage(qo.getPageNum(), qo.getPageSize());
        QueryWrapper<BpmnInfo> bpmnInfoQueryWrapper = new QueryWrapper<>();
        return new TablePageInfo<BpmnInfo>(bpmnInfoMapper.selectList(bpmnInfoQueryWrapper));
    }


    @Override
    @Transactional
    public void deploy(String path, String bpmnType, String info) throws FileNotFoundException {
        //获取文件流
        System.out.println(SystemConfig.getProfile());
        File file = new File(SystemConfig.getProfile(),path);
        //1.部署流程定义对象
        Deployment deploy = repositoryService.createDeployment()
                //第一个参数为限定唯一文件路径名，删除时得用到
                //第二个参数为文件唯一名称
                .addInputStream(path, new FileInputStream(file))
                .deploy();
        //获取流程定义对象
        BpmnInfo bpmnInfo = new BpmnInfo();
        //获取流程部署时间
        bpmnInfo.setDeployTime(new Date());
        //获取流程部署类型
        bpmnInfo.setBpmnType(bpmnType);
        //获取流程id
        bpmnInfo.setDeploymentId(deploy.getId());
        //获取流程备注信息
        bpmnInfo.setInfo(info);

        //2.获取流程定义部署查询对象
        ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery()
                .deploymentId(bpmnInfo.getDeploymentId())
                .singleResult();
        //获取流程定义key
        bpmnInfo.setActProcessKey(processDefinition.getKey());
        //流程定义id
        bpmnInfo.setActProcessId(processDefinition.getId());
        //获取流程定义名称
        bpmnInfo.setBpmnName(processDefinition.getName());
        //流程定义对象封装好的数据传递给数据库
        bpmnInfoMapper.insert(bpmnInfo);
    }

    //展示视图
    @Override
    public InputStream readResourceOrType(String deploymentId, String type) throws IOException {
        // 查看流程文件
        //获取流程定义对象
        ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery()
                .deploymentId(deploymentId)
                .singleResult();
        //判断是否为该流程的实例的类型是否为服务类型的xml或bpmn视图
        if ("xml".equalsIgnoreCase(type)){
            //根据部署ID,查询流程定义对象，通过流程定义对象获取resourceName
            return repositoryService.getResourceAsStream(deploymentId, processDefinition.getResourceName());
        }else if ("png".equalsIgnoreCase(type)){
            //根据部署ID,查询流程定义对象,通过流程定义ID获取BpmnModel对象
            BpmnModel bpmnModel = repositoryService.getBpmnModel(processDefinition.getId());
            //根据插件提供的方法，获取图片的输入流
            DefaultProcessDiagramGenerator defaultProcessDiagramGenerator = new DefaultProcessDiagramGenerator();
            // generateDiagram(bpmn模型对象,需要高亮哪些节点,需要高亮的连线)
            return defaultProcessDiagramGenerator.generateDiagram(bpmnModel, Collections.emptyList()
                    , Collections.emptyList(), "宋体", "宋体", "宋体");
        }
        return null;
    }

    @Override
    public BpmnInfo queryByType(String car_package) {
        QueryWrapper<BpmnInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("bpmn_type",car_package);
        BpmnInfo bpmnInfo = bpmnInfoMapper.selectOne(wrapper);
        return bpmnInfo;
    }


    @Override
    public void deleteDeployment(Long id) {
        //通过id去数据库获取bpmnInfo对象
        BpmnInfo bpmnInfo = this.getById(id);
        //删除流程定义对象
        bpmnInfoMapper.deleteById(id);
        //TODO 方案一:先查询所有的流程实例，找到对应BusinessKey,找到业务数据，把业务数据设置初始化
        //TODO 方案二: 挂起流程定义,然正在运行的流程实例，督促都处理完，都处理完之后，在进行流程定义的删除. （待补充）
        //获取流程自定义对象,如果为服务类型则进行删除
        ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery()
                .processDefinitionKey(bpmnInfo.getActProcessKey())
                .singleResult();
        if ("car_package".equalsIgnoreCase(bpmnInfo.getBpmnType())) {
            repositoryService.deleteDeployment(bpmnInfo.getDeploymentId(),true);
        }
        //获取服务中的文件对象
        String resourceName = processDefinition.getResourceName();
        File file = new File(SystemConfig.getProfile(), resourceName);
        if (file.exists()){
            //file文件直带一个删除文件功能
            file.delete();
        }
    }
}
